package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //当前第几页
        Long pageNo = pageParams.getPageNo();

        //每页有几条
        Long pageSize = pageParams.getPageSize();

        //查询用的课程名字
        String courseName = queryCourseParamsDto.getCourseName();

        //审核状态
        String auditStatus = queryCourseParamsDto.getAuditStatus();

        //发布状态
        String publishStatus = queryCourseParamsDto.getPublishStatus();

        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(courseName), CourseBase::getName, courseName);
        queryWrapper.eq(StringUtils.isNotEmpty(auditStatus), CourseBase::getAuditStatus, auditStatus);
        queryWrapper.eq(StringUtils.isNotEmpty(publishStatus), CourseBase::getStatus, publishStatus);
        Page<CourseBase> page = new Page<>(pageNo, pageSize);
        Page<CourseBase> page1 = courseBaseMapper.selectPage(page, queryWrapper);
        List<CourseBase> courseBases = page1.getRecords();
        long total = page1.getTotal();
        PageResult<CourseBase> pageResult = new PageResult<>(courseBases, total, pageNo, pageSize);
        return pageResult;

    }

    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {

        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBase);
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
        //机构id
        courseBase.setCompanyId(companyId);
        //添加时间
        courseBase.setCreateDate(LocalDateTime.now());

        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0) {
            throw new XueChengPlusException("添加课程失败");
        }
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        //拿到课程id
        Long courseId = courseBase.getId();
        courseMarket.setId(courseId);
        //保存营销信息
        saveCourseMarket(courseMarket);
        //把新增完后的数据查出来返回给前端
        return getCourseBaseInfo(courseId);

    }

    //查询课程信息
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        //从课程基本信息表和营销表查询然后组装
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            throw new XueChengPlusException("查询课程信息失败");
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);

        if (courseMarket == null) {
            throw new XueChengPlusException("无课程销售信息");
        }
        BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);

        String mt = courseBase.getMt();
        String st = courseBase.getSt();
        CourseCategory mt1 = courseCategoryMapper.selectById(mt);
        CourseCategory st1 = courseCategoryMapper.selectById(st);
        courseBaseInfoDto.setMtName(mt1.getName());
        courseBaseInfoDto.setStName(st1.getName());
        return courseBaseInfoDto;
    }


    //单独写一个方法，保存营销信息，存在则更新，不存在则添加
    private int saveCourseMarket(CourseMarket courseMarketNew) {
        String charge = courseMarketNew.getCharge();
        if (!StringUtils.isNotEmpty(charge)) {
            throw new XueChengPlusException("收费规则不能为空");
        }
        if (charge.equals("201001")) {
            if (courseMarketNew.getPrice() == null || courseMarketNew.getPrice() <= 0) {
                throw new XueChengPlusException("收费规则不能为空,并且必须大于0");
            }
        }
        Long id = courseMarketNew.getId();
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if (courseMarket == null) {
            //插入数据库
            int insert = courseMarketMapper.insert(courseMarketNew);
            return insert;
        } else {
            //更新数据库
            BeanUtils.copyProperties(courseMarketNew, courseMarket);
            courseMarket.setId(id);
            int i = courseMarketMapper.updateById(courseMarket);
            return i;
        }
    }

    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) {

        Long courseId = dto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            throw new XueChengPlusException("课程不存在");
        }
//        if (!companyId.equals(courseBase.getCompanyId())){
//            throw new XueChengPlusException("本机构只能修改本机构的课程");
//        }
        BeanUtils.copyProperties(dto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        courseBaseMapper.updateById(courseBase);
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        BeanUtils.copyProperties(dto, courseMarket);

        saveCourseMarket(courseMarket);
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }

    @Override
    @Transactional
    public void deleteCourse(Long id) {
        //先删除课程基本信息
        courseBaseMapper.deleteById(id);
        //再删除课程营销信息
        courseMarketMapper.deleteById(id);
        //删除课程计划
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, id);
        //删除课程教师
        LambdaQueryWrapper<CourseTeacher> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseTeacher::getCourseId, id);
    }

}
